# @time     :2021/12/31
# @Author   :Simple
# @FileName :test
import configparser
import os

import allure
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager


@allure.feature("必应搜索")
class Test01:
    def get_config(self):
        config = configparser.ConfigParser()
        config.read(os.path.join(os.environ['HOME'], "selenium_demo.ini"))
        return config

    @pytest.fixture(scope="class")
    def prepare(self):
        # 获取配置文件
        print("测试开始")
        config = self.get_config()

        # 启动无界面模式运行
        try:
            using_headless = os.environ["using_headless"]
        except KeyError:
            using_headless = None
            print("没有配置环境变量using_headless, 按照有界面方式执行自动化测试")

        chrome_options = Options()
        if using_headless is not None and using_headless.lower() == 'true':
            print("使用无界面方式运行")
            chrome_options.add_argument("--headless")

        self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
        self.driver.implicitly_wait(5)
        yield self.driver
        # 测试结束，关闭driver
        print("测试结束")
        self.driver.quit()

    @allure.story("测试1")
    def test01(self, prepare):
        self.driver = prepare
        with allure.step("打开必应"):
            self.driver.get("https://www.bing.com")
        with allure.step("点击搜索"):
            by = (By.XPATH, "//input[@id='sb_form_q']")
            input = WebDriverWait(self.driver, 10).until(expected_conditions.visibility_of_element_located(by))
            input.send_keys("selenium测试")
            submit = self.driver.find_element(By.XPATH, "//label[@id='search_icon']")
            submit.click()
        by1 = (By.XPATH, "//input[@id='sb_form_q' and @class='b_searchbox']")
        input_btn = WebDriverWait(self.driver, 10).until(expected_conditions.visibility_of_element_located(by1))
        assert(input_btn.text, 'selenium测试')
